<template>
  <div class="app-container">
    <div class="two-col-layout">
      <!--部门数据---->
      <div class="pane left-pane" style="width: 20%;">
        <div class="head-container">
          <el-input v-model="deptName" placeholder="请输入部门名称" clearable prefix-icon="Search"
                    style="margin-bottom: 20px"/>
        </div>
        <div class="head-container">
          <el-tree :data="deptOptions" :props="{ label: 'label', children: 'children' }" :expand-on-click-node="false"
                   :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current default-expand-all
                   @node-click="handleNodeClick"/>
        </div>
      </div>
      <!--项目数据---->
      <div class="pane right-pane" style="width: 80%;">
        <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
          <el-form-item label="项目名称" prop="name">
            <el-input v-model="queryParams.name" placeholder="请输入项目名称" clearable style="width: 240px"
                      @keyup.enter="handleQuery"/>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5" v-if="roleId">
            <el-button type="primary" plain @click="handleProject">设置项目</el-button>
          </el-col>
          <el-col :span="1.5" v-if="roleId">
            <el-button type="warning" plain icon="Close" @click="handleClose">关闭</el-button>
          </el-col>
        </el-row>

        <el-table v-loading="loading" ref="tableRef" :data="projectList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" type="index" width="80"/>
          <el-table-column label="项目名称" align="center" key="name" prop="name" :show-overflow-tooltip="true"/>
          <el-table-column label="排序" align="center" key="sort" prop="sort"/>
          <el-table-column label="归属组织机构" align="center" key="deptName" prop="deptName"
                           :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" key="remark" prop="remark" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
            <template #default="scope">
              <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改
              </el-button>
              <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum"
                    v-model:limit="queryParams.pageSize" @pagination="getList"/>
      </div>
    </div>
    <!-- 添加或修改养老项目对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body :close-on-click-modal="false">
      <el-form ref="projectRef" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="项目名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入项目名称"/>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0"/>
        </el-form-item>
        <el-form-item label="归属组织机构" prop="deptId">
          <el-tree-select v-model="form.deptId" :data="enabledDeptOptions"
                          :props="{ value: 'id', label: 'label', children: 'children' }"
                          @change="chooseDept(enabledDeptOptions,form.deptId)"
                          value-key="id" placeholder="请选择归属部门" clearable check-strictly/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Project">
import {
  listProject,
  getProject,
  delProject,
  addProject,
  updateProject,
} from "@/views/pg/pensionProject/api/project.js";
import {deptTreeSelect} from "@/api/system/user.js";
import useAppStore from "@/store/modules/app.js";
import {
  addRoleProject,
  listIdsRoleProject,
} from "@/views/pg/pensionProject/api/roleProject.js";
import {useRoute} from "vue-router";

const route = useRoute();
const {proxy} = getCurrentInstance();

const projectList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const deptName = ref("");
const deptOptions = ref(undefined);
const enabledDeptOptions = ref(undefined);
const roleId = computed(() => route.query.id);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: null,
    sort: null,
    remark: null,
    deptId: null,
    affiliatedCompany: null,
  },
  rules: {
    name: [{required: true, message: "项目名称不能为空", trigger: "blur"}],
    deptId: [
      {required: true, message: "归属组织机构不能为空", trigger: "blur"},
    ],
    affiliatedCompany: [
      {required: true, message: "归属公司不能为空", trigger: "blur"},
    ],
  },
});

const {queryParams, form, rules} = toRefs(data);

onMounted(() => {
  console.log("pagePath:project")
})

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.label.indexOf(value) !== -1;
};

getDeptTree();

onMounted(() => {
  getList();
});

function getRoleProjectList() {
  loading.value = true;
  listIdsRoleProject({roleId: roleId.value}).then((response) => {
    ids.value = response.data;
    // 在数据加载完成后设置选中状态
    nextTick(() => {
      setTableSelection();
    });
  });
}

// 设置表格选中项
function setTableSelection() {
  if (ids.value && ids.value.length > 0 && projectList.value.length > 0) {
    // 遍历表格数据，找到匹配的项进行选中
    projectList.value.forEach((item) => {
      if (ids.value.includes(item.id)) {
        proxy.$refs.tableRef?.toggleRowSelection(item, true);
      }
    });
  }
}

/** 查询养老项目列表 */
function getList() {
  loading.value = true;
  listProject(queryParams.value).then((response) => {
    projectList.value = response.rows;
    total.value = response.total;
    if (roleId.value) getRoleProjectList();
    loading.value = false;
  });
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
    enabledDeptOptions.value = filterDisabledDept(
        JSON.parse(JSON.stringify(response.data))
    );
  });
}

/** 过滤禁用的部门 */
function filterDisabledDept(deptList) {
  return deptList.filter((dept) => {
    if (dept.disabled) {
      return false;
    }
    if (dept.children && dept.children.length) {
      dept.children = filterDisabledDept(dept.children);
    }
    return true;
  });
}

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.deptId = data.id;
  handleQuery();
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    name: null,
    sort: 0,
    remark: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deleteStatus: "0",
    deptId: null,
    affiliatedCompany: null,
  };
  proxy.resetForm("projectRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加养老项目";
}

// 归属组织机构 只能选择公司或子公司
function chooseDept(treeData, deptId) {
  if (!treeData || !Array.isArray(treeData)) return null;

  for (let node of treeData) {
    if (node.id === deptId) {
      if (node.label && !node.label.includes("公司")) {
        proxy.$modal.msgError("请选择公司或子公司");
        form.value.deptId = null;
        return;
      }
    }
    if (node.children && node.children.length > 0) {
      chooseDept(node.children, deptId);
    }
  }
}

function handleProject() {
  if (!ids.value || !ids.value.length) {
    proxy.$modal.msgError("请选择要设置的项目");
    return;
  }
  let data = {
    roleId: roleId.value,
    projectIds: ids.value,
  };
  addRoleProject(data).then((res) => {
    proxy.$modal.msgSuccess("设置成功");
  });
}

/** 返回按钮操作 */
function handleClose() {
  const obj = {path: "/system/role"};
  proxy.$tab.closeOpenPage(obj);
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getProject(_id).then((response) => {
    form.value = response.data;
    open.value = true;
    title.value = "修改养老项目";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["projectRef"].validate((valid) => {
    if (valid) {
      if (form.value.id != null) {
        updateProject(form.value).then((response) => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProject(form.value).then((response) => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal
      .confirm('是否确认删除？')
      .then(function () {
        return delProject(_ids);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {
      });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
      "pensionProject/project/export",
      {
        ...queryParams.value,
      },
      `project_${new Date().getTime()}.xlsx`
  );
}
</script>
<style>
.default-theme {
  width: 100%;
}

.two-col-layout {
  display: flex;
  gap: 16px;
  width: 100%;
  align-items: stretch;
}

.pane {
  background: #fff;
  border: 1px solid var(--el-border-color, #ebeef5);
  border-radius: 8px;
  padding: 16px;
  box-sizing: border-box;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.04);
}

.left-pane {
  /* 可选：让左侧在内容较长时可滚动 */
  overflow: auto;
}
</style>